%%%-------------------------------------------------------------------
%%% @author admin
%%% @copyright (C) 2022, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 25. 十一月 2022 18:19
%%%-------------------------------------------------------------------
-module(pub_data_svr).
-author("admin").

-include("db_load.hrl").

%% API
-export([init/1, handle_call/3, handle_cast/2, handle_info/2]).
-export([start/0, start_link/0]).

-record(state, {}).

start() ->
    supervisor:start_child(pub_data_svr_sup,[]).

start_link() ->
    gen_server:start_link(?MODULE, [], []).

init(_Args) ->
    gen_server:cast(self(), init),
    {ok, #state{}}.

handle_call(Request, From, State) ->
    do_call(Request, From, State).

handle_cast(Request, State) ->
    do_cast(Request, State).

handle_info(Request, State) ->
    do_info(Request, State).


%% ===========================================================
do_call(_Msg, _, State) ->
    {reply, ok, State}.


do_cast(init, State) ->
    init_load(),
    {noreply, State};
do_cast(flush, State) ->
    flush(),
    {noreply, State};
do_cast(_Request, State) ->
    {noreply, State}.


do_info(init, State) ->
    init_load(),
    {noreply, State};
do_info(flush, State) ->
    flush(),
    {noreply, State};
do_info(_Request, State) ->
    {noreply, State}.

%% ==========================================================
init_load() ->
    ets:new(?TABLE_PUB_DATA, [public, named_table, {keypos, 1}]),
    Datas= db_load:mutl_kv_all_load(?TABLE_PUB_DATA),
    ets:insert(?TABLE_PUB_DATA, Datas),
    erlang:send_after(5000, self(), flush),
    ok.

flush() ->
    receive
        flush -> flush()
    after
        0 -> do_flush()
    end.

do_flush() ->
    Data = ets:tab2list(?TABLE_PUB_DATA),
    db_load:mult_kv_save(?TABLE_PUB_DATA, Data),
    erlang:send_after(5000, self(), flush),
    ok.